package com.knife.blog.web.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.fileupload.FileItem;

import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.Photo;
import com.knife.blog.logic.HTMLGenerater;
import com.knife.blog.logic.ImgService;
import com.knife.blog.logic.PhotoService;
import com.knife.blog.logic.impl.BlogCircleServiceImpl;
import com.knife.blog.logic.impl.BlogPhotoDirServiceImpl;
import com.knife.blog.logic.impl.BlogUserServiceImpl;
import com.knife.blog.logic.impl.PhotoServiceImpl;
import com.knife.blog.service.Config;
import com.knife.blog.util.BlogFileUtil;
import com.knife.util.CommUtil;
import com.knife.util.FileUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.tools.IActiveUser;
import com.knife.web.tools.IPageList;

public class BlogPhotoAction extends BaseCrudAction {
	private static PhotoService photoService = PhotoServiceImpl.getInstance();

	public Object doBefore(WebForm form, Module module) {
		if(this.getCurrentUser(form)!=null){
			blog = userService.getUserBlog(this.getCurrentUser(form).getUserName());
		}else{
			String username = (String)form.get("username");
			if(username!=null&&!username.equals(""))
				blog = userService.getUserBlog(username);
		}
		return super.doBefore(form, module);
	}
	@Override
	public IPageList doQuery(WebForm form, int currentPage, int pageSize) {
		String username = CommUtil.null2String(this.getCurrentUser(form).getUserName());
		return photoService.queryPhoto(username,
				currentPage, pageSize);
	}

	public Page doAdd(WebForm form, Module module, IActiveUser user) {
		Photo obj = (Photo) form2Obj(form);
		obj.setInputuser(user.getUserName());
		obj.setReplynum(0);
		obj.setReadtimes(0);
		obj.setBlogcid(userService.getUserBlog(user.getUserName()).getCid());
		obj.setInputtime(new java.util.Date());

		FileItem file = (FileItem) form.get("file");
		if (file != null) {
			String clientName = file.getName();
			if (!BlogFileUtil.isImgageFile(clientName)) {
				form.addResult("msg", "只能上传图片文件及附件文件！");
				return module.findPage("edit");
			} else{
				uploadFile(file, obj);
			}
		}else{
			form.addResult("msg", "上传失败！");
			return module.findPage("edit");
		}
		boolean ret = photoService.addPhoto(obj);
		if (ret) {
			blog.setUpdated(Boolean.TRUE);
			String circleSn = (String)form.get("circlesn");
			if(circleSn!=null&&!circleSn.equals("")){
				BlogInfo blogInfo = userService.getBlogInfo(circleSn);
				blogInfo.setUpdated(Boolean.TRUE);
				userService.settingBlogInfo(blogInfo);
			}
			userService.settingBlogInfo(blog);
			form.addResult("msg", "添加成功!");
			/*if(((String)form.get("window")).equals("modalDialog")){
				String clientName = file.getName();
				form.addResult("fileName", obj.getUrl());
				form.addResult("clientName", clientName.substring(clientName
						.lastIndexOf("\\") + 1));
				return module.findPage("photoUpload");
			}*/
			return super.doQuery(form, module, user);
		} else {
			form.addResult("msg", "添加失败!");
			return module.findPage("edit");
		}
	}

	public Page doDel(WebForm form, Module module, IActiveUser user) {
		String cid = (String) form.get("cid");
		boolean ret = photoService.delPhoto(cid);
		form.addResult("msg", ret ? "删除成功!" : "删除失败!");
		return super.doQuery(form, module, user);
	}

	public Page doUpdate(WebForm form, Module module, IActiveUser user) {
		boolean ret = photoService.updatePhoto((Photo) form2Obj(form));
		form.addResult("msg", ret ? "修改成功!" : "修改失败!");
		return super.doQuery(form, module, user);
	}

	public Page doListPhoto(WebForm form, Module module){
		String dir = (String)form.get("dir");
		String username = (String)form.get("username");
		int currentPage = CommUtil.null2Int(form.get("page"));
		int pageSize = CommUtil.null2Int(form.get("pageSize"));
		if (currentPage < 1)
			currentPage = 1;
		if (pageSize < 1)
			pageSize = 15;
		IPageList pageList = photoService.queryPhoto(dir, username, currentPage, pageSize);
		CommUtil.saveIPageList2WebForm(pageList, form);
		if (pageList != null)
			form.addResult("pageSize", new Integer(pageSize));
		return new Page("photo" + blog.getUsername(), "/blog/template/"
				+ blog.getTemplate() + "/photo.html","template");
	}

	public Page doUpload(WebForm form, Module module){
		List list = photoService.queryPhotoDir(this.getCurrentUser(form).getUserName(),0,-1).getResult();
		form.addResult("list",list);
		form.addResult("circleService", BlogCircleServiceImpl.getInstance());
		return module.findPage("photoUpload");
	}

	public Page doImgUpload(WebForm form, Module module){
		/*String username = this.getCurrentUser(form).getUserName();
		List list = photoService.queryPhotoDir(username,0,-1).getResult();
		List circleList = BlogCircleServiceImpl.getInstance().queryAllUserCircle(username).getResult();
		form.addResult("list",list);
		form.addResult("circlelist",circleList);*/

		return module.findPage("photoDialog");
	}

	public Page doVisitCount(WebForm form, Module module){
		String cid = CommUtil.null2String(form.get("cid"));
		Photo photo = photoService.readPhoto(cid);
		return null;
	}

	public Object form2Obj(WebForm form) {
		String cid = CommUtil.null2String(form.get("cid"));
		Photo obj = photoService.getPhoto(cid);
		if (obj == null)
			obj = new Photo();
		form.toPo(obj);
		return obj;
	}

	public void uploadFile(FileItem file, Photo obj) {
		String clientName = file.getName();
		FileUtil.isImgageFile(clientName);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		if (file != null) {
			String filePath = Config.getWwwpath()  + "/"+blog.getDomain()+"/photo/"+df.format(obj.getInputtime())
					 + "/";
			File fdir = new File(filePath);
			if (!fdir.exists())
				fdir.mkdirs();
			try {
				String fileName = (clientName.substring(clientName.lastIndexOf(File.separator) + 1)).split("\\.")[1];
				fileName = CommUtil.getRandString(8)+"."+fileName;
				file.write(new File(filePath + fileName));
				obj.setUrl("/photo/" + df.format(obj.getInputtime()) + "/" + fileName);
				String s_fileName = "s_"+fileName;
				String s_url = "/photo/" + df.format(obj.getInputtime()) + "/" + s_fileName;
				ImgService is = new ImgService(filePath, filePath, fileName, s_fileName);
				if(is.CreateThumbnail(120,120))
					obj.setS_url(s_url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}